package services

import (
	"errors"
	"fmt"
	"github.com/beego/beego/v2/client/orm"
	"time"
	"weiboxs.com/new_h_glasses/models"
	"weiboxs.com/new_h_glasses/utils"
)

type ErpFlowingService struct {
}

func (s *ErpFlowingService) createFlowingNumber() string {
	stat := utils.GetDateParse(time.Now().Format("2006-01-02"))
	end := stat + 86400

	//查询当日流水单数量
	query := orm.NewOrm().QueryTable(models.ErpFlowingTableName())
	cond := orm.NewCondition()
	cond = cond.AndCond(cond.And("flowing_date__gte", stat).And("flowing_date__lte", end))
	query = query.SetCond(cond)
	count, _ := query.Count()
	//end
	return fmt.Sprintf("%s%06d", time.Now().Format("20060102150405"), count+1)
}

//增加流水表信息
func (s *ErpFlowingService) SaveErpFlowing(o orm.TxOrmer, data *models.ErpFlowing) error {
	//生成入库单据号
	if len(data.FlowingUser) <= 0 {
		return errors.New("操作人不能为空")
	}
	if data.FlowingNum <= 0 {
		return errors.New("数量小于0")
	}
	if data.DepartmentId <= 0 {
		return errors.New("所属门店不能为空")
	}
	if data.Typeid <= 0 {
		return errors.New("单据类型不能为空")
	}
	data.Number = s.createFlowingNumber()
	data.FlowingDate = time.Now().Unix()
	data.IsFlushing = 2
	if _, err := o.Insert(data); err != nil {
		return err
	}
	return nil
}

//增加流水明细表信息
func (s *ErpFlowingService) SaveErpFlowingData(o orm.TxOrmer, flo *models.ErpFlowing, datas []*models.ErpFlowingData) error {

	if len(datas) <= 0 {
		return errors.New("流水明细数据不能为空")
	}

	chkProduct := make(map[int64]int)  //存储产品ID用于减少数据查询

	//数据验证
	for k, _ := range datas {
		if datas[k].DepartmentId == 0 {
			return errors.New("流水所属门店不能为空")
		}
		if datas[k].Typeid == 0 {
			return errors.New("流水单据类型不能为空")
		}
		if datas[k].Products.Id == 0 {
			return errors.New("流水产品不能为空")
		}
		if datas[k].StorageNum == 0 {
			return errors.New("流水库存变动数量不能为空")
		}

		if _,ok := chkProduct[datas[k].Products.Id]; !ok {  //需要查询产品类型
			var typeid int
			if err := o.Raw("SELECT type_id as typeid FROM "+models.ErpProductsTableName()+" WHERE id=?", datas[k].Products.Id).QueryRow(&typeid); err != nil {
				return err
			}
			chkProduct[datas[k].Products.Id] = typeid
		}
		if chkProduct[datas[k].Products.Id] != 50 && chkProduct[datas[k].Products.Id] != 60 && chkProduct[datas[k].Products.Id] != 70 {
			if datas[k].Snd.Id == 0 {
				return errors.New("Snd流水参数错误")
			}
		}
		datas[k].CreatedAt = time.Now().Unix()
		if flo != nil {
			datas[k].Flowing = flo
		}
	}

	//批量写入数据
	if _, err := o.InsertMulti(len(datas), datas); err != nil {
		return err
	}
	return nil
}

